package com.hn658.base.service.common;


import java.util.Properties;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.ServletHandler;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.ConfigUtils;
/**
 * 应用启动接着启动jetty服务
 * @author davidcun
 *
 */
public class JettyServerInterceptor extends LauncherInterceptorAdapter {
	
	private static final String JETTY_PROPERTIES = "META-INF/config/jetty.properties";
	private static final int DEFAULT_PORT = 9090;
	
	private static final Logger logger = LoggerFactory.getLogger(JettyServerInterceptor.class);
	
	private static Properties prop;
	
	public JettyServerInterceptor() {
		loadProperties();
	}
	
	private void loadProperties(){
		try{
			prop = ConfigUtils.loadProperties(JETTY_PROPERTIES, false, true);
		}catch(Exception e){
			logger.error("load jetty.properties error", e);
			prop = new Properties();
		}
	}
	
	@Override
	public void beforeStart() {
		Server server = new Server();
		SelectChannelConnector scc = new SelectChannelConnector();
		
		String pt = prop.getProperty("port");
		
		scc.setPort( pt != null ? Integer.valueOf(pt) : DEFAULT_PORT  );
		
		server.addConnector(scc);

		ServletHandler handler = new ServletHandler();
		server.addHandler(handler);
		try {
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
